package com.gistmap.ecepoi.web;

import com.gistmap.ecepoi.common.ExcelService;
import com.gistmap.ecepoi.common.ExcelUtils;
import com.gistmap.ecepoi.domain.User;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import static java.util.stream.IntStream.range;

/**
 * @author zhangran
 * @date 2018/7/2
 */
@RestController
@Slf4j
public class ExcelController {

    @Autowired
    private ExcelUtils excelUtils;

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment; filename=" + java.net.URLEncoder.encode("test", "UTF-8") + ".xls");

        List<User> list = Lists.newArrayList();
        range(1,10).forEach(i -> {
            User user = new User(i, 18+i);
            list.add(user);
        });
        excelUtils.export(response.getOutputStream(), list, User.class);
    }

    @PostMapping("/import")
    public List<User> importExcel(@RequestParam("upload_file") MultipartFile uploadFile) throws IOException {

        if (uploadFile == null) {
            log.info("文件不存在");
        }
        if (!excelUtils.isExcel(uploadFile.getOriginalFilename())) {
            log.info("请上传excel文件");
        }
        List<User> objects = excelUtils.excel2Data(uploadFile.getOriginalFilename(), uploadFile.getInputStream(), User.class);

        return objects;
    }
}
